/*
 * DependencyInjectionHttpServlet.java
 * Copyright (c) 2009 Khronos
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */
package ar.com.cema.methodology.analyzer.ui.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


/**
 * {@link HttpServlet} al que puede aplicarsele inyeccion de dependencias.
 *
 * @author <a href="mailto:tezequiel@gmail.com">Ezequiel Turovetzky</a>
 *
 */
public abstract class DependencyInjectionHttpServlet extends HttpServlet {

	//~ Methods ----------------------------------------------------------------
	private static final long serialVersionUID = 151899667268683506L;

	@Override
    public final void init() throws ServletException {
    	try {
    		ApplicationContext ctx = getApplicationContext();
    		AutowireCapableBeanFactory beanFactory = ctx.getAutowireCapableBeanFactory();
    		beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_NO, false);
    		beanFactory.initializeBean(this, getClass().getName());
    	} catch(Exception e) {
    		throw new ServletException("Error injecting dependencies on servlet '" + getServletName() + "': " + e.getMessage(), e);
    	}
    	postInit();
    }
    
    /**
     * Permite a las subclases extender la inicializacion del servlet.
     * <p>Este metodo se invoca una vez terminada la inyeccion de dependencias llevada
     * a cabo en el metodo {@link #init()}.
     * <p>
     * Por defecto, este metodo no hace nada.
     * @throws ServletException En caso de error
     */
    protected void postInit() throws ServletException {
    }

    /**
     * Devuelve el {@link ApplicationContext} asociado al contexto web de este servlet.
     * @return El {@link ApplicationContext} asociado al contexto web de este servlet
     */
    protected ApplicationContext getApplicationContext() {
        return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    }
}
